package com.aspire.boc.mms.gwcmp.action;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.xmlrpc.XmlRpcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.aspire.boc.mms.gwcmp.model.GwcmpProduct;
import com.aspire.boc.mms.gwcmp.model.GwcmpProductExample;
import com.aspire.boc.mms.gwcmp.model.GwcmpProductExample.Criteria;
import com.aspire.boc.mms.gwcmp.service.ProductService;
import com.aspire.boc.mms.gwcmp.util.Constants;
import com.aspire.boc.mms.gwcmp.util.GwcmpAdminUtil;
import com.aspire.boc.mms.wmf.util.Configuration;
import com.aspire.boc.mms.wmf.util.Json;
import com.aspire.boc.mms.wmf.util.Page;


/**
 * 产品管理
* @ClassName: ProductAct 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author zhouzhendong
* @date 2016年1月14日  
*
 */

@Controller
public class ProductAct {

    private static Log logger = LogFactory.getLog(ProductAct.class);
    
    @Autowired
    private ProductService productService;
      
   /**
    * 查询产品列表
    * @param id
    * @param productName
    * @param ecId
    * @param start
    * @param limit
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value="/product/getProductList")
    @ResponseBody
    public Map<String, Object> getProductList(
            @RequestParam(value = "id", required = false) String id,
            @RequestParam(value = "productName", required = false) String productName,
            @RequestParam(value = "ecId", required = false) String ecId,
            @RequestParam(value = "start", required = true) int start,
            @RequestParam(value = "limit", required = true) int limit,
            HttpServletRequest request, HttpServletResponse response) {
    	String operator= GwcmpAdminUtil.getLoginUserName(request);	
		logger.info("operator: "+ operator+",operation:getProductList, url:/product/getProductList"
				+ ", params[ id:"+ id + ",productName:"+ productName + ",ecId:"+ ecId 
				+ ",start:"+ start + ",limit:" + limit + "]");
        HashMap<String, Object> map = new HashMap<String, Object>();
        Map<String,Object> param = new HashMap<String, Object>();
		Page page = new Page(start, limit);
		param.put("page", page);
        if(StringUtils.isNotBlank(id))param.put("id", "%"+id+"%");
        if(StringUtils.isNotBlank(productName))param.put("productName", "%"+productName+"%");
        if(StringUtils.isNotBlank(ecId)) param.put("ecId", ecId);
        List<GwcmpProduct> products =null;
        int total=0;
        try {
            // 系统管理员、业务管理员可操作
//            PermissionManage pm = PermissionUtil.getPermissionManage(request);
//            if(!pm.isSystemAdmin() && !pm.isBusinessAdmin()) {
//                logger.error(">>>>>>>>>>operator: "+getLoginUser(request).getAdminName()+", operation: queryProducts, not system admin or business admin, privileges insufficient");
//                return map;
//            }
        	products = productService.getProductList(param);
            total =  productService.countProductList(param);
          
            logger.info("operator: "+operator+", operation: getProductList, result: total="+total+",productsSize:"+products.size());
        } catch(Exception e) {
        	logger.error("operator: "+operator+", operation: getProductList, errorMsg: ",e);        
        }
        map.put("list", products);
        map.put("total", total);
        return map;
    }
   /**
    * 查询(上线且计费未占用产品)
    * @param productName
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value="/product/getNoOccupiedProductList")
    @ResponseBody
    public Map<String, Object> getNoOccupiedProductList(            
            @RequestParam(value = "productName", required = false) String productName,        
            HttpServletRequest request, HttpServletResponse response) {
		
    	String operator= GwcmpAdminUtil.getLoginUserName(request);	
		logger.info("operator: "+ operator+",operation:getNoOccupiedProductList, url:/product/getNoOccupiedProductList"
				+ ", params[productName:"+ productName + "]");
        HashMap<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        if(StringUtils.isNotBlank(productName)){	       
	        param.put("productName", "%"+productName+"%");     
        }
        List<GwcmpProduct> products =null;
        try {
            // 系统管理员、业务管理员可操作
//            PermissionManage pm = PermissionUtil.getPermissionManage(request);
//            if(!pm.isSystemAdmin() && !pm.isBusinessAdmin()) {
//                logger.error(">>>>>>>>>>operator: "+getLoginUser(request).getAdminName()+", operation: queryProducts, not system admin or business admin, privileges insufficient");
//                return map;
//            }
            products = productService.getNoOccupiedProductList(param);        
            logger.info("operator: "+operator+", operation: getNoOccupiedProductList, result:productsSize:"+products.size());
        } catch(Exception e) {
        	logger.error("operator: "+operator+", operation: getNoOccupiedProductList, errorMsg: ",e);        
        }
        map.put("list", products);
        return map;
    }
    
   /**
    * 获取产品详情
    * @param id
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value="/product/getProductDetail")
    @ResponseBody
    public Map<String, Object> getProductDetail(
            @RequestParam(value = "id", required = false) String id,
            HttpServletRequest request, HttpServletResponse response) {
    	Map<String, Object> result = new HashMap<String, Object>();
		RequestContext requestContext = new RequestContext(request);    	
    	String operator= GwcmpAdminUtil.getLoginUserName(request);	
		logger.info("operator: "+ operator+",operation:getProductDetail, url:/product/getProductDetail"
				+ ", params[ id:"+ id + "]");   
		GwcmpProduct gwcmpProduct = null;
    	if (StringUtils.isBlank(id)) {
    		logger.error("operator:"+operator+",operation:getProductDetail ,[id] is null");
			result.put("failure", Boolean.valueOf(true));
			result.put("msg",requestContext.getMessage("product.error.productIdNotExist"));
			return result; 
		}
        try {
            // 系统管理员、业务管理员可操作
//            PermissionManage pm = PermissionUtil.getPermissionManage(request);
//            if(!pm.isSystemAdmin() && !pm.isBusinessAdmin()) {
//                logger.error(">>>>>>>>>>operator: "+getLoginUser(request).getAdminName()+", operation: queryProducts, not system admin or business admin, privileges insufficient");
//                return map;
//            }
        	gwcmpProduct = productService.selectByPrimaryKey(id);
            logger.info("operator: "+operator+", operation: getProductDetail, result: [gwcmpProduct:"+gwcmpProduct+"]");
        } catch(Exception e) {
        	logger.error("operator: "+operator+", operation: getProductDetail, errorMsg: ",e);  
        }
        result.put("single", gwcmpProduct);
        return result;
    }
    /**
     * 保存产品  ，新增和修改
     * @param id
     * @param productName
     * @param ecId
     * @param serviceType
     * @param businessType
     * @param cmccChannelId
     * @param cmccChannelSrcid
     * @param cmccChannelExtParams
     * @param unicomChannelId
     * @param unicomChannelSrcid
     * @param unicomChannelExtParams
     * @param telcomChannelId
     * @param telcomChannelSrcid
     * @param telcomChannelExtParams
     * @param priority
     * @param needAudit
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/product/saveProduct")
    @ResponseBody
    public ResponseEntity<String> saveProduct(
            @RequestParam(value = "id", required = false) String id,
            @RequestParam(value = "productName", required = true) String productName,
            @RequestParam(value = "ecId", required = true) String ecId,
            @RequestParam(value = "serviceType", required = true) short serviceType,
            @RequestParam(value = "businessType", required = true) short businessType,
            @RequestParam(value = "cmccChannelId", required = false) String cmccChannelId,
            @RequestParam(value = "cmccChannelSrcid", required = false) String cmccChannelSrcid,
            @RequestParam(value = "cmccChannelExtParams", required = false) String cmccChannelExtParams,
            @RequestParam(value = "unicomChannelId", required = false) String unicomChannelId,
            @RequestParam(value = "unicomChannelSrcid", required = false) String unicomChannelSrcid,
            @RequestParam(value = "unicomChannelExtParams", required = false) String unicomChannelExtParams,
            @RequestParam(value = "telcomChannelId", required = false) String telcomChannelId,
            @RequestParam(value = "telcomChannelSrcid", required = false) String telcomChannelSrcid,
            @RequestParam(value = "telcomChannelExtParams", required = false) String telcomChannelExtParams,
            @RequestParam(value = "priority", required = true) short priority,
            @RequestParam(value = "needAudit", required = true) short needAudit,
            HttpServletRequest request, HttpServletResponse response) {
    	
    	RequestContext requestContext = new RequestContext(request);
    	String operator= GwcmpAdminUtil.getLoginUserName(request);
    	StringBuffer sb = new StringBuffer();
		sb.append("operator: " + operator
				+ ",operation:saveProduct, url:/product/saveProduct,");
		sb.append("params[")
				.append("id:" + id + ",productName:" + productName 
						+ ",ecId:"+ ecId + ",serviceType:" + serviceType)
				.append(",cmccChannelExtParams:" + cmccChannelExtParams)
				.append(",unicomChannelId:" + unicomChannelId)
				.append(",unicomChannelSrcid:" + unicomChannelSrcid)
				.append(",unicomChannelExtParams" + unicomChannelExtParams)
				.append(",telcomChannelId:" + telcomChannelId)
				.append(",telcomChannelSrcid:" + telcomChannelSrcid)
				.append(",telcomChannelExtParams:" + telcomChannelExtParams)
				.append(",priority:" + priority)
				.append(",needAudit:" + needAudit)
				.append("]");
		logger.info(sb.toString());
        Map<String, Object> result = new HashMap<String, Object>();
        GwcmpProduct gwcmpProduct = new GwcmpProduct();        
        if (StringUtils.isBlank(productName)||productName.length()>50) {
        	result.put("failure", Boolean.valueOf(true));
            logger.info("operator: "+operator+", operation: saveProduct, errorMsg: productName Wrong");
            return returnErrorResponse(result, requestContext.getMessage("product.error.productNameWrong"));
		}
        gwcmpProduct.setProductName(productName);
      
        if (StringUtils.isBlank(ecId)) {
        	result.put("failure", Boolean.valueOf(true));
            logger.info("operator: "+operator+", operation: saveProduct, errorMsg: ecIdNotExits");
            return returnErrorResponse(result, requestContext.getMessage("product.error.ecIdNotExist"));

        }
        gwcmpProduct.setEcId(ecId);   
        
        String regex="[0-9]*";     
        //服务种类
        gwcmpProduct.setServiceType(serviceType);
        //业务类型
        gwcmpProduct.setBusinessType(businessType);
       
        gwcmpProduct.setCmccChannelId(cmccChannelId);     
        if (StringUtils.isNotBlank(cmccChannelSrcid)) {
          	if(!(regexCheck(regex, cmccChannelSrcid)&&cmccChannelSrcid.length()<20)){
	       		result.put("failure", Boolean.valueOf(true));
	            logger.info("operator: "+operator+", operation: saveProduct, errorMsg: cmccChannelSrcidWrong");
	            return returnErrorResponse(result, requestContext.getMessage("product.error.cmccChannelSrcid"));
	       	}
		}
        gwcmpProduct.setCmccChannelSrcid(cmccChannelSrcid);
        gwcmpProduct.setCmccChannelExtParams(cmccChannelExtParams);
	      
        gwcmpProduct.setUnicomChannelId(unicomChannelId);
        if (StringUtils.isNotBlank(unicomChannelSrcid)) {
          	if(!(regexCheck(regex, unicomChannelSrcid)&&unicomChannelSrcid.length()<20)){ 		  
          	   result.put("failure", Boolean.valueOf(true));
               logger.info("operator: "+operator+", operation: saveProduct, errorMsg: unicomChannelSrcidWrong");
               return returnErrorResponse(result, requestContext.getMessage("product.error.unicomChannelSrcid"));
          	}
        }
        gwcmpProduct.setUnicomChannelSrcid(unicomChannelSrcid);
        gwcmpProduct.setUnicomChannelExtParams(unicomChannelExtParams);
		
       
        if (StringUtils.isNotBlank(telcomChannelSrcid)) {
          	if(!(regexCheck(regex, telcomChannelSrcid)&&telcomChannelSrcid.length()<20)){ 		         
          	   result.put("failure", Boolean.valueOf(true));
               logger.info("operator: "+operator+", operation: saveProduct, errorMsg: telcomChannelSrcidWrong");
               return returnErrorResponse(result, requestContext.getMessage("product.error.telcomChannelSrcid"));        	
          	} 
        }
        gwcmpProduct.setTelcomChannelId(telcomChannelId);
        gwcmpProduct.setTelcomChannelSrcid(telcomChannelSrcid);       
        gwcmpProduct.setTelcomChannelExtParams(telcomChannelExtParams);
             
        //优先级
        gwcmpProduct.setPriority(priority);
        //是否审核
        gwcmpProduct.setNeedAudit(needAudit);
        gwcmpProduct.setLatestOperateTime(new Date());
		gwcmpProduct.setLatestOperator(operator);
		
		GwcmpProductExample example = new GwcmpProductExample();
		Criteria cc=example.createCriteria();	
		if(StringUtils.isNotBlank(id)){
			cc.andIdNotEqualTo(id);
		}
		cc.andProductNameEqualTo(productName);
		int count=productService.countByExample(example);
		if(count!=0){
			result.put("failure", Boolean.valueOf(true));
            logger.info("operator: "+operator+", operation: saveProduct, errorMsg: productNameNotRepeat");
            return returnErrorResponse(result, requestContext.getMessage("product.error.productNameNotRepeat"));
		}
		
        try {
            // 系统管理员、业务管理员可操作
//            PermissionManage pm = PermissionUtil.getPermissionManage(request);
//            if(!pm.isSystemAdmin() && !pm.isBusinessAdmin()) {
//                result.put("failure", Boolean.valueOf(true));
//                result.put("msg", "权限不足");
//                logger.error(">>>>>>>>>operator: "+currUserName+", operation: saveProduct, not system admin or business admin, privileges insufficient");
//                return new ResponseEntity<String>(Json.toJson(result), getHttpHeaders(), HttpStatus.OK);
//            }
        	// 向权限系统中插入数据和更新数据
        	Object object = new Object();
     	    XmlRpcClient client = new XmlRpcClient(
     	    		Configuration.getConfiguration("system.permission.url"));
     	    Vector<Object> params = new Vector<Object>();
     	    params.add(Configuration.getConfiguration("system.permission.system_def"));
    	    params.add("ProductAdmin");//产品为ProductAdmin，企业为EcAdmin    
     	    Hashtable hash = new Hashtable();
     	    hash.put("data_name", gwcmpProduct.getProductName());
     	    hash.put("data_descr", "");
     	    hash.put("enroll_date", new Date());
     	    hash.put("user_name", operator);  
     	    
        	if(StringUtils.isBlank(id)){
        		int seq_id=productService.getProductIdSequence();  	        
    	        gwcmpProduct.setId(seq_id+"");
    	        gwcmpProduct.setStatus(Constants.PRODUCT_OFF);
    	        productService.insertSelective(gwcmpProduct);
            }else{
            	GwcmpProduct productOld = productService.selectByPrimaryKey(id);
            	if(productOld==null){
       	            logger.error("operator: "+ operator+ ",operation: saveProduct, errorMeg:productNotExist");
       	            return returnErrorResponse(result, requestContext.getMessage("product.error.productNotExist"));
            		
            	}
            	if (productOld.getStatus()==1) {
            		logger.error("operator: "+ operator+ ",operation: saveProduct, errorMeg:productOn");
            		return returnErrorResponse(result, requestContext.getMessage("product.error.productOn"));
				}
            	gwcmpProduct.setId(id);
            	productService.updateByPrimaryKeySelective(gwcmpProduct);   	
        	    //更新数据
            	hash.put("data_id", Integer.valueOf(gwcmpProduct.getId()));
            	params.add(hash);
        	    object = client.execute(
        	           "FineGrainedResService.updateDataRow", params);
        	    logger.info("[" + operator+ "][saveProduct update permission Product]["
        	           +  gwcmpProduct.getId() + "]["
        	           +  gwcmpProduct.getProductName() + "]" + object);         	
            }
            result.put("success", Boolean.valueOf(true));
            logger.info("operator: "+operator+", operation: saveProduct , result: successful, productobject: "+gwcmpProduct);
           
        } catch(Exception e) {
            logger.error("operator: "+operator+", operation: saveProduct, errorMsg: ",e);
            return returnErrorResponse(result, requestContext.getMessage("common.error.systemError"));
        }
        return new ResponseEntity<String>(Json.toJson(result), getHttpHeaders(), HttpStatus.OK);
    }

    /**
     * 上下线产品
     * @param productIds
     * @param status
     * @param request
     * @param response
     * @return
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/product/changeProductStatus")
    @ResponseBody
    public ResponseEntity<String> changeProductStatus(
    		@RequestParam(value = "productIds", required = true) String productIds,
    		@RequestParam(value = "status", required = true) Short status,
    		HttpServletRequest request, HttpServletResponse response){
    	
    	RequestContext requestContext = new RequestContext(request);
    	String operator= GwcmpAdminUtil.getLoginUserName(request);	
		logger.info("operator: "+ operator+",operation:changeProductStatus, url:/product/changeProductStatus"
				+ ", params[ productIds:"+ productIds + ",status:"+ status + "]");
    	Map<String,Object> result = new HashMap<String,Object>();
    	
    	if (StringUtils.isBlank(productIds)) {
    		logger.info("operator: "+operator+", operation: changeProductStatus, errorMsg:productIdNotExist");
    		return returnErrorResponse(result, requestContext.getMessage("product.error.productIdNotExist"));
    	}
    	if(!(status==1||status==0)){
    		logger.info("operator: "+operator+", operation: changeProductStatus, errorMsg:productIdNotExist");
    		return returnErrorResponse(result, requestContext.getMessage("product.error.status"));
    	}
    	
    	String[] ids=productIds.split(",");
    	try {
	    	for (String id : ids) {    		
				if (StringUtils.isNotBlank(id)) {
					GwcmpProduct product=productService.selectByPrimaryKey(id);					
					GwcmpProduct gwcmpProduct = new GwcmpProduct();
					gwcmpProduct.setId(id);
					gwcmpProduct.setStatus(status);
					gwcmpProduct.setLatestOperateTime(new Date());
					gwcmpProduct.setLatestOperator(operator);
					
					productService.updateByPrimaryKeySelective(gwcmpProduct);
					Object object = new Object();
					XmlRpcClient client = new XmlRpcClient(
							Configuration.getConfiguration("system.permission.url"));
					Vector<Object> params = new Vector<Object>();
					Hashtable hash = new Hashtable();
					hash.put("data_id", Integer.valueOf(product.getId()));
					hash.put("data_name", product.getProductName());
					params.add(Configuration.getConfiguration("system.permission.system_def"));
					params.add("ProductAdmin");
					
					if(status==0){
						// 删除权限系统中的数据
						params.add(hash);
						object = client.execute("FineGrainedResService.deleteDataRow",
								params);
						logger.info("["+ operator+ "][freezeProduct delete permission Product][productId="
								+ id + "][productName=" + product.getProductName()
								+ "][result=" + object + "]");
					}else{	
						hash.put("data_descr", "");
			     	    hash.put("enroll_date", new Date());
			     	    hash.put("user_name", operator);
			     	    params.add(hash);
			     	    object = client.execute(
		    	               "FineGrainedResService.addDataRow", params);
		    	        logger.info("[" + operator+ "][saveProduct insert permission Product]["
		    	               + product.getProductName() + "]" + object);
					}
				}
			}
	    	result.put("success", Boolean.valueOf(true));
			logger.info("operator: "+operator+", operation: changeProductStatus, result: successful");  
		} catch (Exception e) {
			logger.error("operator: "+operator+", operation: changeProductStatus, errorMsg: ",e);
            return returnErrorResponse(result, requestContext.getMessage("common.error.systemError"));
		}
    	
      return new ResponseEntity<String>(Json.toJson(result), getHttpHeaders(), HttpStatus.OK);
    }
    
   /**
    * 导出产品订单
    * @param id
    * @param productName
    * @param ecId
    * @param request
    * @param response
    * @throws Exception
    */
	@RequestMapping(value = "/product/exportProductList")
	@ResponseBody
	public void exportProductList(
			 @RequestParam(value = "id", required = false) String id,
			 @RequestParam(value = "productName", required = false) String productName,
			 @RequestParam(value = "ecId", required = false) String ecId,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
    	String operator= GwcmpAdminUtil.getLoginUserName(request);   	
		logger.info("operator:"+operator+",url:/productOrder/exportProductOrder, params[id: "
				+ id + ",productName:"+productName+",ecId: " + ecId+"]");
		
		 Map<String,Object> param = new HashMap<String, Object>();
		
        if(StringUtils.isNotBlank(id))param.put("id", "%"+id+"%");
        if(StringUtils.isNotBlank(productName))param.put("productName", "%"+productName+"%");
        if(StringUtils.isNotBlank(ecId)) param.put("ecId", ecId);

		List<GwcmpProduct> list = productService.getProductList(param);
		HSSFWorkbook wb = writeOrderInfo2ExcelOutputStream(list, response);
		String filename = "CPGL__"
				+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
				+ ".xls";
		downloadExcel(wb, filename, response);
		logger.info(">>>>>>>> success to export product order, count=" + list == null ? 0
				: list.size());
	}

	/**
	 * 批量操作
	 * @param productIds 
	 * @param cmccChannelId
	 * @param unicomChannelId
	 * @param telcomChannelId
	 * @param priority
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/product/batchEditProducts")
	@ResponseBody
	public ResponseEntity<String> batchEditProducts(
			@RequestParam(value = "productIds", required = false) String productIds,
			@RequestParam(value = "cmccChannelId", required = false) String cmccChannelId,
			@RequestParam(value = "unicomChannelId", required = false) String unicomChannelId,
			@RequestParam(value = "telcomChannelId", required = false) String telcomChannelId,
			@RequestParam(value = "priority", required = false) Short priority,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {		
		RequestContext requestContext = new RequestContext(request);
    	String operator= GwcmpAdminUtil.getLoginUserName(request);	
		logger.info("operator: "+ operator+",operation:batchUpdateProduct, url:/product/batchUpdateProduct"
				+ ", params[ cmccChannelId:"+ cmccChannelId + ",unicomChannelId:"+ unicomChannelId 
				+ "telcomChannelId:"+ telcomChannelId + ",priority:"+ priority + "]");
    	Map<String,Object> result = new HashMap<String,Object>();
    	
    	if (StringUtils.isBlank(productIds)) {	
    		logger.info("operator: "+operator+", operation: batchUpdateProduct, errorMsg:productIdNotExist ");
    		return returnErrorResponse(result, requestContext.getMessage("product.error.productIdNotExist"));
    	}
    	try {
	    	//判断是否 通道或优先级必选一个
	    	boolean ret=StringUtils.isNotBlank(cmccChannelId)||StringUtils.isNotBlank(unicomChannelId)
	    			||StringUtils.isNotBlank(telcomChannelId)||priority!=null;
	    	if(!ret){
	    		logger.info("operator: "+operator+", operation: batchUpdateProduct, errorMsg:nendChannelIdOrPriority ");
	    		return returnErrorResponse(result, requestContext.getMessage("product.error.nendChannelIdOrPriority"));
	    	}else{
	    		String[] ids=productIds.split(",");
		    	for (String id : ids) {    		
					if (StringUtils.isNotBlank(id)) {
						//GwcmpProduct product=productService.selectByPrimaryKey(id);
						//是否能修改
						GwcmpProduct gwcmpProduct = new GwcmpProduct();
						gwcmpProduct.setId(id);
						if (StringUtils.isNotBlank(cmccChannelId))
							gwcmpProduct.setCmccChannelId(cmccChannelId);
						if (StringUtils.isNotBlank(unicomChannelId))
							gwcmpProduct.setUnicomChannelId(unicomChannelId);
						if (StringUtils.isNotBlank(telcomChannelId))
							gwcmpProduct.setTelcomChannelId(telcomChannelId);
						if (priority != null)
							gwcmpProduct.setPriority(priority);
						gwcmpProduct.setLatestOperateTime(new Date());
						productService.updateByPrimaryKeySelective(gwcmpProduct);		
				}
	    	}
    	}
    	result.put("success", Boolean.valueOf(true));
		logger.info("operator: "+operator+", operation: batchUpdateProduct, result: successful");  
		} catch (Exception e) {       
            logger.error("operator: "+operator+", operation: batchUpdateProduct, errorMsg: ",e);
            return returnErrorResponse(result, requestContext.getMessage("common.error.systemError"));
		}	
      return new ResponseEntity<String>(Json.toJson(result), getHttpHeaders(), HttpStatus.OK);
	
	}

    /**
     * 获取http消息头
     * @return
     */
    private HttpHeaders getHttpHeaders() {  
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType mediaType = new MediaType("text", "html", Charset.forName("utf-8"));
        httpHeaders.setContentType(mediaType);
        return httpHeaders;
    }
    
    /**
     * 返回响应消息
     * @param result
     * @param errMsg
     * @return
     */
    private ResponseEntity<String> returnErrorResponse(Map<String, Object> result, String errMsg) {
        result.put("failure", Boolean.valueOf(true));
        result.put("msg", errMsg);
        return new ResponseEntity<String>(Json.toJson(result), getHttpHeaders(), HttpStatus.OK);
    }
    
	/**
	 * 创建工作量excel文件
	 * @param products 产品列表
	 * @param response 
	 * @return
	 */
	private HSSFWorkbook writeOrderInfo2ExcelOutputStream(
			List<GwcmpProduct> products, HttpServletResponse response) {
		String[] titles={"产品ID","产品名称","关联企业","企业ID","业务类型","服务种类","通道信息","优先级"};
		
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFCellStyle numStyle = wb.createCellStyle();
		numStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
		int size = products == null ? 0 : products.size();
		if (size > 0) {
			int sheetSize = 5000;
			int sheetCount = (int) Math.ceil(size / sheetSize + 1);
			
			for (int n = 0; n < sheetCount; n++) {
				HSSFSheet sheet = wb.createSheet("表" + (n + 1));
				sheet.setDefaultColumnWidth((short) 10);
				HSSFRow rowHead = sheet.createRow(0);
				for (int i = 0; i < titles.length; i++) {
					rowHead.createCell((short) i).setCellValue(
							new HSSFRichTextString(titles[i]));				
				}
				// 10001: 0-4999, 5000-9999, 10000-10001
				for (int i = n * sheetSize; i < products.size()
						&& i < (n + 1) * sheetSize; i++) {
					HSSFRow rowBody = sheet.createRow(i % sheetSize + 1);
					GwcmpProduct product = products.get(i);
					//产品ID、产品名称、关联企业、企业ID
					rowBody.createCell((short) 0).setCellValue(new HSSFRichTextString(product
											.getId()));
					rowBody.createCell((short) 1).setCellValue(
							new HSSFRichTextString(product.getProductName()));
					rowBody.createCell((short) 2).setCellValue(
							new HSSFRichTextString(product.getEcName()));
					rowBody.createCell((short) 3).setCellValue(
							new HSSFRichTextString(product.getEcId()));
					// 业务类型、服务种类、、优先级。
					
					rowBody.createCell((short)4).setCellValue(
							new HSSFRichTextString(formatBusinessType(product.getBusinessType()))
							);	
					rowBody.createCell((short)5).setCellValue(
							new HSSFRichTextString(formatServiceType(product
									.getServiceType()))
							);		
					//通道信息
					
					rowBody.createCell((short)6).setCellValue(
							new HSSFRichTextString(getChannalName(product))
							);	
					rowBody.createCell((short) 7).setCellValue(
							new HSSFRichTextString(formatPriority(product
									.getPriority())));
				}
			}
		}
		return wb;
	}
	/**
	 * 获取通道信息
	 * @param product
	 * @return
	 */
	private String getChannalName(GwcmpProduct product) {
		String  channelName="";
		String cmccChannelName=product.getCmccChannelName();
		if(StringUtils.isNotBlank(cmccChannelName))
			channelName += cmccChannelName + ',';
		String unicomChannelName =product.getUnicomChannelName();
		if(StringUtils.isNotBlank(unicomChannelName))
			channelName +=unicomChannelName + ',';
		String telcomChannelName =product.getTelcomChannelName();
		if(StringUtils.isNotBlank(telcomChannelName))
			channelName +=telcomChannelName + ',';	
		if(StringUtils.isNotBlank(channelName)){
			channelName = channelName.substring(0, channelName.length()-1);
		}
		return channelName;
	}
	/**
	 * 转换业务类型
	 * @param businessType  1:三网;2:移动;3:联通;4:电信;
	 * 5:联通、电信;6:移动、联通;7:移动、电信
	 * @return
	 */
	private String formatServiceType(Short serviceType) {
		String type = "";	
		if(serviceType!=null){	
			if (serviceType == 1) {
				type = "三网";
			} else if (serviceType == 2) {
				type = "移动";
			} else if (serviceType == 3) {
				type = "联通";
			}else if (serviceType == 4) {
				type = "电信";
			}else if (serviceType == 5) {
				type = "联通、电信";
			}else if (serviceType == 6) {
				type = "移动、联通";
			}else if (serviceType == 7) {
				type = "移动、电信";
			}
		}
		return type;
	}

	//	将优先级的数值转换成字符串1:低;2:中;3:高
	private String formatPriority(Short priority) {
		String type = "";	
		if(priority!=null){	
			if (priority == 1) {
				type = "低";
			} else if (priority == 2) {
				type = "中";
			} else if (priority == 3) {
				type = "高";
			}
		}
		return type;
	}
	//	业务类型1:彩信;2:短信
	private String formatBusinessType(Short businessType) {
		String type = "";
		if(businessType!=null){	
			if (businessType == 1) {
				type = "彩信";
			} else if (businessType == 2) {
				type = "短信";
			}
		}
		return type;
	}
	/**
	 * 正则校验
	 * @param regex 正则规则
	 * @param msg	校验内容
	 * @return
	 */
	private boolean regexCheck(String regex,String msg){
		if(msg==null||regex==null){
			return false;
		}
		Pattern pattern = Pattern.compile(regex);  
		Matcher matcher = pattern.matcher(msg); 
		return matcher.matches();
	}
 
	/**
	 * @param wb
	 * @param filename
	 * @param response
	 */
	private void downloadExcel(HSSFWorkbook wb, String filename,
			HttpServletResponse response) {

		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setHeader("Content-Type", "application/force-download");
			response.setHeader("Content-Disposition", "attachment;filename="
					+ URLEncoder.encode(filename, "UTF-8"));
			wb.write(out);
			out.close();
		} catch (Exception e) {
			logger.error(">>>>>fail to write output stream", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.error(">>>>>fail to close output stream", e);
				}
			}
		}
	}
}
